package com.nongcai159.mall.lib_common.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import java.lang.ref.WeakReference

/**
 * 主界面fragment基类
 *
 *
 * Created by tanbiheng on 2018/11/26.
 */

abstract class BaseFragment : Fragment() {
    var isFragmentFinish = false// UI是否关闭
    var isFragmentForground = false// UI是否在后台
    var isFragmentHidden = false// UI是否可见

    var mHandler: FragmentWeakReferenceHandler? = null

    var activity: Activity? = null

    /**
     * 绑定fragment布局到窗口
     */
    abstract val createView: Int

    override fun onAttach(context: Context?) {
        super.onAttach(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isFragmentFinish = false
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(createView,
                container, false)

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        activity = ActivityStackManager.INSTANCE.currentActivity()
        if (activity == null) {
            activity = getActivity()
        }
        initFragment(view)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isFragmentHidden = hidden
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
        isFragmentForground = true

    }

    override fun onPause() {
        super.onPause()
        isFragmentForground = false

    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        isFragmentFinish = true

        if (mHandler != null) {
            mHandler!!.removeCallbacksAndMessages(null)
            mHandler = null
        }
    }

    override fun onDetach() {
        super.onDetach()
    }

    fun handleMyMessage(msg: Message) {

    }

    class FragmentWeakReferenceHandler(activity: BaseFragment) : Handler() {
        private val mFragment: WeakReference<BaseFragment>

        init {
            mFragment = WeakReference(activity)
        }

        override fun handleMessage(msg: Message) {
            if (mFragment.get() == null) {
                return
            }
            (mFragment.get() as BaseFragment).handleMyMessage(msg)
        }
    }

    /**
     * 初始化UI
     */
    abstract fun initFragment(view: View)
}
